package org.jxf.gps.jt808.message;

import java.util.HashMap;
import java.util.Map;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

/**
 * 根据808协议规则起止符为0x7E，对粘包及半包进行处理。
 * @author jxf
 * 2015年1月20日
 */
public class JT808FrameDecoder extends FrameDecoder{
	
	/**
	 * 记录每个channel中的半包，以便和下一个半包进行补齐
	 */
	private static Map halfPkgPool = new HashMap();
	
	private byte start = 0x7E;
	private byte end = 0x7E;

	/**
	 *对粘包进行分组处理，不完整的包将被保留，并与下一个不完整的包进行合并
	 *例如：7E0200002A9131971848730006000000050087B94301D16F7D068C237103220000001E15011922081701040001E848020200640302029E0A7E7E0200002A9131971848730006000000050087B94301D16F7D068C237103220000001E15011922081701040001E848020200640302029E0A7E
	 */
	@Override
	protected Object decode(ChannelHandlerContext ctx, Channel channel,
			ChannelBuffer buffer) throws Exception {
		// TODO Auto-generated method stub
		ChannelBuffer frame;
		byte[] a = new byte[buffer.array().length];
		int count = 0;
        for (int i = buffer.readerIndex(); i < buffer.writerIndex(); i ++) {
            int idx = i;
            byte b = buffer.readByte();
            if (0x7E == b){
            	if (count == 0){//开始符
            		a[count] = b;
            	}else{//终止符
            		a[count] = b;
            		frame = ChannelBuffers.buffer(count+1);
            		frame.writeBytes(a, 0, count+1);
            		return frame;
            	}
            }else{
            	if (count == 0){//没有7E开始标识符的包
            		byte[] last = (byte[])halfPkgPool.get(channel.getId());
            		System.arraycopy(last, 0, a, 0, last.length);
            		count = last.length;
            	}
            	a[count] = b;
            }
            count++;
        }		
        byte[] firstHalf = new byte[count];
        System.arraycopy(a, 0, firstHalf, 0, count);
        halfPkgPool.put(channel.getId(), firstHalf);
		return null;
	}
}
